<template>
  <div>
    <table class="table table-sm table-bordered table-vertical-middle approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tr class="bg-light">
        <td colspan="4" class="text-center py-2">诉讼信息</td>
      </tr>
      <tr>
        <td>开庭时间</td>
        <td :class="tdClass">
          <span v-if="isView">{{ $utils.dateFormat(formData.court_time, dateFor) }}</span>
          <el-date-picker
            v-else
            type="date"
            class="w-100"
            value-format="yyyy-MM-dd"
            placeholder="开庭时间"
            v-model="formData.court_time"
          ></el-date-picker>
        </td>
        <td>诉讼登记时间</td>
        <td>
          <span v-if="isView">
            {{ $utils.dateFormat(formData.court_register_time, dateFor) }}
          </span>
          <span v-else>
            {{ $utils.dateFormat(new Date(), dateFor) }}
          </span>
        </td>
      </tr>
      <tr>
        <td>开庭附件</td>
        <td colspan="3">
          <template v-if="isView">
            <div v-for="file in areadyFiles" :key="file.url" class="d-flex">
              <attach-item :attach-data="file"></attach-item>
            </div>
          </template>
          <template v-else>
            <div class="d-flex align-items-stretch p-2">
              <div class="mr-3">
                <input
                  type="file"
                  ref="uploadInput"
                  class="d-none"
                  multiple
                  accept="*"
                  @change="handleFileChange"
                />
                <el-button
                  plain
                  size="small"
                  class="mb-1"
                  icon="el-icon-upload2"
                  style="height: 100%"
                  :disabled="saveLoading"
                  @click="handleSelectFile"
                >
                  上传
                </el-button>
              </div>
              <div class="flex-1 bg-light p-2 rounded">
                <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                  <attach-item :attach-data="file"></attach-item>
                  <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                    删除
                  </el-button>
                </div>
                <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                  <attach-item :attach-data="file"></attach-item>
                  <el-button
                    type="text"
                    :disabled="saveLoading"
                    @click="handleDeleteFile(2, index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </td>
      </tr>
    </table>

    <div class="text-center my-3" v-if="!isView">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="submit">
        诉讼登记
      </el-button>

      <el-button class="btn-long" @click="beforClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { uploadOss, deleteOss } from '@/common/api/oss'
import AttachItem from '@/bank/components/attach/Item'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
export default {
  components: {
    AttachItem,
  },
  props: {
    queryId: String,
    lawsuitData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
  },
  data() {
    return {
      saveLoading: false,
      dateFor: 'yyyy-MM-dd',
      tableName: 'litigation_register',
      formData: {},
      areadyFiles: [],
      uploadFiles: [],
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['user']),
    tdClass() {
      return this.isView ? '' : 'report-input-td'
    },
    isView() {
      return this.viewMode
    },
    tableId() {
      return this.lawsuitData.litigation_register_id || ''
    },
  },
  watch: {
    lawsuitData: {
      handler: function () {
        this.areadyFiles = []
        this.uploadFiles = []
        this.formData = { ...this.lawsuitData }
        this.init()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      this.areadyFiles = arrayFromString(this.formData.court_attachment).reduce((prev, curr) => {
        prev.push(
          attachAdapter({
            attachment: curr,
          })
        )
        return prev
      }, [])
    },
    submit() {
      if (!this.validate()) {
        return false
      }
      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/lawsuit/${this.queryId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])

          const data = {
            customer_related_id: this.queryId,
            court_time: this.formData.court_time,
            court_register_time: this.$utils.dateFormat(new Date()),
            court_attachment: attachment || '',
            is_court: 1,
          }
          return this.tableId
            ? this.$api.updateData(this.$serviceName, this.tableName, this.tableId, data)
            : this.$api.addData(this.$serviceName, this.tableName, {
                ...data,
                submit_person_name: this.user.realName,
              })
        })
        .then(() => {
          this.$emit('success')
          this.$message.success('保存成功')
        })
        .finally(() => {
          this.deleteOssFiles()
          this.saveLoading = false
        })
    },
    validate() {
      if (!this.queryId) {
        this.$message.error('请选择登记项目')
        return false
      }
      const enumValidator = {
        court_time: '请选择开庭时间',
      }
      for (const key of Object.keys(enumValidator)) {
        if (!this.formData[key]) {
          this.$message.error(enumValidator[key])
          return false
        }
      }

      return true
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },
    beforClose() {
      this.$emit('dismiss')
    },
  },
}
</script>

<style lang="scss" scoped>
.approve-table {
  text-align: center;
  margin-bottom: 0;
  margin-top: -1px;
  td {
    vertical-align: middle;
  }
}
.file-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
</style>
